import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    View,
    Text, TouchableOpacity, Image, SectionList, FlatList, ActivityIndicator,
} from 'react-native';
import Header from "../../../components/header";
import StatusBarSelf from "../../../components/StatusBarSelf";
import Loading from "../../../utils/Loading";
import Constant from "../../../utils/Constant";
import {getImgUrl, getPerm} from "../../../utils/ComFunction";
import NoData from "../../../utils/NoData";
import HttpUtils from "../../../utils/HttpUtils";
import HttpUrls from "../../../utils/HttpUrls";
import BuyerListPage from "../../seekCenter/BuyerListPage";
import BuyerItemView from "../../seekCenter/seekComponents/BuyerItemView";
import {PermissionType} from "../../../utils/Enum";

let navigation

export default class CarPublishSuccessPage extends Component {

    constructor(props) {
        super(props);
        this.hasMounted = false; // 添加挂载状态标志
        let purchaseCenterPerm = getPerm(PermissionType.Permission_EnablePurchaseCenter)
        const { carId, action, backPage } = this.props.route.params || {};
        this.state = {
            purchaseCenterPerm,
            carId: carId,
            action: action,
            backPage: backPage,
            buyerLists: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
        }
    }

    componentDidMount() {
        if(this.state.purchaseCenterPerm){
            this.hasMounted = true; // 确保组件已挂载
            this.refreshData();
        }
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <StatusBarSelf color={'#fff'}/>
                {/*<Header navigation={navigation} Title={'fa'} ></Header>*/}

                <View style={{ width: '100%', flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
                    <Image style={{width: 60, height: 60, marginTop: 30}} source={require('source/image/icon_selector_checked.png')} />
                    <Text style={{ fontSize: 16, color: '#333333',marginTop:20 }}>{this.state.action === 'add' ? '车辆发布成功' : '车辆编辑成功'}</Text>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        console.log('返回', this.state.backPage);
                        if(this.state.backPage){
                            navigation.replace(this.state.backPage);
                        }else {
                            navigation.replace('CarStockListPage');
                        }
                    }}>
                        <View style={{height: 30, width: 70, backgroundColor: '#FFE000', marginTop: 20, borderRadius: 5, justifyContent: 'center', alignItems: 'center'}}>
                            <Text style={{color: '#333333', fontSize: 14}}>返回</Text>
                        </View>
                    </TouchableOpacity>
                </View>

                {
                    this.state.purchaseCenterPerm > 0 && (
                        <View>
                            <View style={styles.recommendationSection}>
                                <View style={styles.separator} />
                                <Text style={styles.recommendationTitle}>买手推荐</Text>
                                <View style={styles.separator} />
                            </View>

                        </View>
                    )
                }

                {/* 列表数据 */}
                {this.state.purchaseCenterPerm > 0 ? this.renderList() : null}
                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        )
    }

    renderList() {
        return (
            <View
                style={{
                    flex: 1,
                    // height: 200,
                    // marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                    // backgroundColor: 'red',
                }}>

                <FlatList
                    data={this.state.buyerLists}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.1}
                />
            </View>
        );
    }

    renderItemView({item}) {
        return (
            <View>
               <BuyerItemView
                   item={item}
                   onPress={() => {
                       navigation.navigate('BuyerInfoPage', {
                           buyerId: item.buyerId,
                       });
                   }}
               ></BuyerItemView>
            </View>
        );
    }

    renderEmpty() {
        return <NoData Desc="暂无数据" style={{marginTop: gREM(10)}} />;
    }

    //刷新数据
    refreshData = () => {
        this.setState(
            {
                isRefresh: true,
                pageNo: 1,
                buyerLists: [],
            },
            function () {
                this.getBuyerList();
            },
        );
    };

    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        // 如果组件未挂载完成或正在加载，则不触发
        if (!this.hasMounted || this.state.showFoot !== 0) {
            return;
        }
        // 检查是否真的有更多数据可以加载（第一页数据必须满20条才允许加载下一页）
        if (this.state.pageNo === 1 && this.state.buyerLists.length < 20) {
            return;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1,
            },
            function () {
                this.getBuyerList();
            },
        );
    }

    // 买手列表获取
    getBuyerList() {
        let param = {
            pageNo: this.state.pageNo,
            pageSize: 20,
            carId: this.state.carId,
        };
        if(!this.state.carId){
            console.log('carI缺失', param)
        }
        HttpUtils.postRequest(HttpUrls.queryBuyerList, param)
            .then(result => {
                let data = result.data;
                if (data) {
                    let resultList = data.resultList;
                    if (resultList && resultList.length > 0) {
                        this.setState({
                            buyerLists: this.state.buyerLists.concat(resultList),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: resultList.length >= 20 ? 0 : 1,
                            });
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch(error => {});
    }

}

const styles = StyleSheet.create({
    container: {
        // flex: 1,
        height: '100%',
        backgroundColor: '#F9F9F9',
    },
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6',
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    recommendationSection: {
        marginTop: 10,
        // marginBottom: 10,
    },
    separator: {
        height: 1,
        backgroundColor: '#F0F0F0',
    },
    recommendationTitle: {
        fontSize: 17,
        fontWeight: 'bold',
        color: '#333333',
        marginLeft: 15,
        paddingVertical: 10,
    },
})